﻿

using HbcServerProcess.Interfaces;
using IotContract.Dtos.Servers.Pushs;
using IotContract.Interfaces;
using XT.Common.Extensions;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IotContract.Enums;
using IotContract.Models.Clients;
using IotContract.Models.Fmts;
using IotContract.Consts;
using IotContract.Models.Plcs;
using IotContract.Models.Clients.Hks;
using Newtonsoft.Json;
using IotContract.Dtos.Servers.Process;

namespace HbcServerProcess.Services;
public class ProcessDataService : IProcessDataService
{
    private IServerMainManager _mainManager;
    private IEquipValidateService _equipValidateService;
   
   
    
    public ProcessDataService(IServerMainManager mainManager,IEquipValidateService equipValidateService)
    {
        _mainManager = mainManager;
        _equipValidateService = equipValidateService;
       
    }
    /// <summary>
    /// 扫码枪数据
    /// </summary>
    public ConcurrentDictionary<int, List<PushBcrDto>> Bcrs { get; set; } = new ConcurrentDictionary<int, List<PushBcrDto>>();

    /// <summary>
    /// 物流线数据
    /// </summary>
    public ConcurrentDictionary<int, CvUnitTagDto> CvUnitTags { get; set; } = new ConcurrentDictionary<int, CvUnitTagDto>();
    /// <summary>
    /// 堆垛机数据
    /// </summary>
    public ConcurrentDictionary<int, ScUnitDto> ScUnits { get; set; } = new ConcurrentDictionary<int, ScUnitDto>();
    /// <summary>
    /// 充放电设备数据
    /// </summary>
    public List<PushHkOcvFmtDto> Fmts { get; set; } = new List<PushHkOcvFmtDto>();

    /// <summary>
    /// 杭可预约信息
    /// </summary>
    public ConcurrentDictionary<string, HkWriteInstruct> HkFMTAppointDic { get; set; } = new ConcurrentDictionary<string, HkWriteInstruct>();

    /// <summary>
    /// ECS设备状态数据,按照类型分组
    /// </summary>
    public ConcurrentDictionary<IotEquipType, ConcurrentDictionary<int, EquipWarnStatus>> EcsEquipWarnDic { get; set; } = new ConcurrentDictionary<IotEquipType, ConcurrentDictionary<int, EquipWarnStatus>>();

    /// <summary>
    /// 设备状态
    /// </summary>
    public ConcurrentQueue<RemoteEquipStatus> EquipStatusQueue { get; set; }=new ConcurrentQueue<RemoteEquipStatus>();
    /// <summary>
    /// 设备报警
    /// </summary>
    public ConcurrentQueue<RemoteEquipWarn> EquipWarnQueue { get; set; } = new ConcurrentQueue<RemoteEquipWarn>();



    /// <summary>
    /// 写入Cv点位数据
    /// </summary>
    /// <param name="equipTag"></param>
    /// <returns></returns>
    public async Task<bool> WriteCvData(PushEquipTag equipTag)
    {
       return await _mainManager.AddWrite(new IotContract.Models.Clients.OperationWriteCommand
        {
            EquipId = equipTag.EquipInfoId,
            TagId = equipTag.Id,
            Value = equipTag.Value,
            ProtobufType=IotProtobufType.HBC_SIEMENS_S7.ToString()
        });
    }

   
   
    /// <summary>
    /// 写入Ecs CV数据
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<string> WriteCvAddr(EcsCvWrite data)
    {
        try
        {
           var unitTag= CvUnitTags.GetValueOrDefault(data.TagNumber);
            if (unitTag==null)
            {
                return IotMsgConst.NoCvTagError;
            }
            if (data != null)
            {
             
                List<OperationWriteCommand> datas= new List<OperationWriteCommand>();
                string protobufType = IotProtobufType.HBC_SIEMENS_S7.ToString();

               var jobNumber= unitTag.GetTagByProperty("JOB_NUMBER");

                datas.Add(new OperationWriteCommand
                {
                    Value = data.JobNumber.ToString(),
                    EquipId = jobNumber.EquipInfoId,
                    TagId = jobNumber.Id,
                    ProtobufType = protobufType
                }) ;

                var jobType = unitTag.GetTagByProperty("JOB_TYPE");
              
                datas.Add(new OperationWriteCommand
                {
                    Value = data.JobType.ToString(),
                    EquipId = jobType.EquipInfoId,
                    TagId = jobType.Id,
                    ProtobufType = protobufType
                });

                var destNum = unitTag.GetTagByProperty("DEST_NUM");
               
                datas.Add(new OperationWriteCommand
                {
                    Value = data.DestNum.ToString(),
                    EquipId = destNum.EquipInfoId,
                    TagId = destNum.Id,
                    ProtobufType = protobufType
                });

                var trayType = unitTag.GetTagByProperty("TRAY_TYPE");
                
                datas.Add(new OperationWriteCommand
                {
                    Value = data.TrayType.ToString(),
                    EquipId = trayType.EquipInfoId,
                    TagId = trayType.Id,
                    ProtobufType = protobufType
                });
               var result=await _mainManager.AddWrites(datas);
                if (!result)
                {
                    return IotMsgConst.WriteRequestError;
                }
            }

            return string.Empty;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    /// <summary>
    /// 写入
    /// </summary>
    /// <param name="addr"></param>
    /// <returns></returns>
   public async Task<string> WriteScAddr(ScUnitDto sc, PlcSCAddr addr)
    {
        try
        {
            {

                List<OperationWriteCommand> datas = new List<OperationWriteCommand>();
                string protobufType = IotProtobufType.HBC_SIEMENS_S7.ToString();

                var jobNumber = sc.GetTagByProperty("W_JOBNUMBER");
                datas.Add(new OperationWriteCommand
                {
                    Value = addr.JobNumber.ToString(),
                    EquipId = jobNumber.EquipInfoId,
                    TagId = jobNumber.Id,
                    ProtobufType = protobufType
                });
                var jobType = sc.GetTagByProperty("W_JOBTYPE");
                datas.Add(new OperationWriteCommand
                {
                    Value = addr.ActionType.ToString(),
                    EquipId = jobType.EquipInfoId,
                    TagId = jobType.Id,
                    ProtobufType = protobufType
                });

                var jobNumber2 = sc.GetTagByProperty("W_JOBNUMBER_FORK2");
                datas.Add(new OperationWriteCommand
                {
                    Value = addr.JobNumber2.ToString(),
                    EquipId = jobNumber2.EquipInfoId,
                    TagId = jobNumber2.Id,
                    ProtobufType = protobufType
                });
                var jobType2 = sc.GetTagByProperty("W_JOBTYPE_FORK2");
                datas.Add(new OperationWriteCommand
                {
                    Value = addr.JobNumber2 > 0 ? addr.ActionType.ToString() : "0",
                    EquipId = jobType2.EquipInfoId,
                    TagId = jobType2.Id,
                    ProtobufType = protobufType
                });
                // 出库
                if (sc.ActionType == 2)
                {
                  
                    var fromBank = sc.GetTagByProperty("W_FROM_BANK");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromBank.ToString(),
                        EquipId = fromBank.EquipInfoId,
                        TagId = fromBank.Id,
                        ProtobufType = protobufType
                    });

                    var fromBay = sc.GetTagByProperty("W_FROM_BAY");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromBay.ToString(),
                        EquipId = fromBay.EquipInfoId,
                        TagId = fromBay.Id,
                        ProtobufType = protobufType
                    });
                    var fromLevel = sc.GetTagByProperty("W_FROM_LEVEL");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromLevel.ToString(),
                        EquipId = fromLevel.EquipInfoId,
                        TagId = fromLevel.Id,
                        ProtobufType = protobufType
                    });
                    var toStation = sc.GetTagByProperty("W_TO_STATION");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToStation.ToString(),
                        EquipId = toStation.EquipInfoId,
                        TagId = toStation.Id,
                        ProtobufType = protobufType
                    });

                  
                    var fromBank2 = sc.GetTagByProperty("W_FROM_BANK_FORK2");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromBank2.ToString(),
                        EquipId = fromBank2.EquipInfoId,
                        TagId = fromBank2.Id,
                        ProtobufType = protobufType
                    });
                    var fromBay2 = sc.GetTagByProperty("W_FROM_BAY_FORK2");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromBay2.ToString(),
                        EquipId = fromBay2.EquipInfoId,
                        TagId = fromBay2.Id,
                        ProtobufType = protobufType
                    });
                    var fromLevel2 = sc.GetTagByProperty("W_FROM_LEVEL_FORK2");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromLevel2.ToString(),
                        EquipId = fromLevel2.EquipInfoId,
                        TagId = fromLevel2.Id,
                        ProtobufType = protobufType
                    });
                    var toStation2 = sc.GetTagByProperty("W_TO_STATION_FORK2");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToStation2.ToString(),
                        EquipId = toStation2.EquipInfoId,
                        TagId = toStation2.Id,
                        ProtobufType = protobufType
                    });
                }
                // 入库
                else if (sc.ActionType == 1)
                {
                    var toBank = sc.GetTagByProperty("W_TO_BANK");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToBank.ToString(),
                        EquipId = toBank.EquipInfoId,
                        TagId = toBank.Id,
                        ProtobufType = protobufType
                    });

                    var toBay = sc.GetTagByProperty("W_TO_BAY");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToBay.ToString(),
                        EquipId = toBay.EquipInfoId,
                        TagId = toBay.Id,
                        ProtobufType = protobufType
                    });
                    var toLevel = sc.GetTagByProperty("W_TO_LEVEL");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToLevel.ToString(),
                        EquipId = toLevel.EquipInfoId,
                        TagId = toLevel.Id,
                        ProtobufType = protobufType
                    });

                    var fromStation = sc.GetTagByProperty("W_FROM_STATION");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromStation.ToString(),
                        EquipId = fromStation.EquipInfoId,
                        TagId = fromStation.Id,
                        ProtobufType = protobufType
                    });

                    var toBank2 = sc.GetTagByProperty("W_TO_BANK_FORK2");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToBank.ToString(),
                        EquipId = toBank.EquipInfoId,
                        TagId = toBank.Id,
                        ProtobufType = protobufType
                    });

                    var toBay2 = sc.GetTagByProperty("W_TO_BAY_FORK2");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToBay2.ToString(),
                        EquipId = toBay2.EquipInfoId,
                        TagId = toBay2.Id,
                        ProtobufType = protobufType
                    });
                    var toLevel2 = sc.GetTagByProperty("W_TO_LEVEL_FORK2");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToLevel2.ToString(),
                        EquipId = toLevel2.EquipInfoId,
                        TagId = toLevel2.Id,
                        ProtobufType = protobufType
                    });

                    var fromStation2 = sc.GetTagByProperty("W_FROM_STATION_FORK2");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromStation2.ToString(),
                        EquipId = fromStation2.EquipInfoId,
                        TagId = fromStation2.Id,
                        ProtobufType = protobufType
                    });
                }
                // 移库
                else if (sc.ActionType == 3)
                {
                    var fromBank = sc.GetTagByProperty("W_FROM_BANK");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromBank.ToString(),
                        EquipId = fromBank.EquipInfoId,
                        TagId = fromBank.Id,
                        ProtobufType = protobufType
                    });

                    var fromBay = sc.GetTagByProperty("W_FROM_BAY");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromBay.ToString(),
                        EquipId = fromBay.EquipInfoId,
                        TagId = fromBay.Id,
                        ProtobufType = protobufType
                    });
                    var fromLevel = sc.GetTagByProperty("W_FROM_LEVEL");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromLevel.ToString(),
                        EquipId = fromLevel.EquipInfoId,
                        TagId = fromLevel.Id,
                        ProtobufType = protobufType
                    });

                    var toBank = sc.GetTagByProperty("W_TO_BANK");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToBank.ToString(),
                        EquipId = toBank.EquipInfoId,
                        TagId = toBank.Id,
                        ProtobufType = protobufType
                    });

                    var toBay = sc.GetTagByProperty("W_TO_BAY");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToBay.ToString(),
                        EquipId = toBay.EquipInfoId,
                        TagId = toBay.Id,
                        ProtobufType = protobufType
                    });
                    var toLevel = sc.GetTagByProperty("W_TO_LEVEL");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToLevel.ToString(),
                        EquipId = toLevel.EquipInfoId,
                        TagId = toLevel.Id,
                        ProtobufType = protobufType
                    });
                }
                // 写完不启动
                else if (sc.ActionType == 0)
                {
                    var fromBank = sc.GetTagByProperty("W_FROM_BANK");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromBank.ToString(),
                        EquipId = fromBank.EquipInfoId,
                        TagId = fromBank.Id,
                        ProtobufType = protobufType
                    });

                    var fromBay = sc.GetTagByProperty("W_FROM_BAY");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromBay.ToString(),
                        EquipId = fromBay.EquipInfoId,
                        TagId = fromBay.Id,
                        ProtobufType = protobufType
                    });
                    var fromLevel = sc.GetTagByProperty("W_FROM_LEVEL");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromLevel.ToString(),
                        EquipId = fromLevel.EquipInfoId,
                        TagId = fromLevel.Id,
                        ProtobufType = protobufType
                    });
                    var toStation = sc.GetTagByProperty("W_TO_STATION");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToStation.ToString(),
                        EquipId = toStation.EquipInfoId,
                        TagId = toStation.Id,
                        ProtobufType = protobufType
                    });

                    var toBank = sc.GetTagByProperty("W_TO_BANK");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToBank.ToString(),
                        EquipId = toBank.EquipInfoId,
                        TagId = toBank.Id,
                        ProtobufType = protobufType
                    });

                    var toBay = sc.GetTagByProperty("W_TO_BAY");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToBay.ToString(),
                        EquipId = toBay.EquipInfoId,
                        TagId = toBay.Id,
                        ProtobufType = protobufType
                    });
                    var toLevel = sc.GetTagByProperty("W_TO_LEVEL");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.ToLevel.ToString(),
                        EquipId = toLevel.EquipInfoId,
                        TagId = toLevel.Id,
                        ProtobufType = protobufType
                    });

                    var fromStation = sc.GetTagByProperty("W_FROM_STATION");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.FromStation.ToString(),
                        EquipId = fromStation.EquipInfoId,
                        TagId = fromStation.Id,
                        ProtobufType = protobufType
                    });

                }

                else if (sc.ActionType == 4)
                {
                    var status = sc.GetTagByProperty("W_STATUE_DATA");
                    datas.Add(new OperationWriteCommand
                    {
                        Value = addr.Command.ToString(),
                        EquipId = status.EquipInfoId,
                        TagId = status.Id,
                        ProtobufType = protobufType
                    });
                    

                }

                if (sc.ActionType != 0)
                {
                    // 启动
                    var dataRun = sc.GetTagByProperty("W_JOB_DATA_WRITE");
                    datas.Add(new OperationWriteCommand
                    {
                        Value =sc.ActionType==4?"0": "1",
                        EquipId = dataRun.EquipInfoId,
                        TagId = dataRun.Id,
                        ProtobufType = protobufType
                    });
                }

                var result = await _mainManager.AddWrites(datas);
                if (!result)
                {
                    return IotMsgConst.WriteRequestError;
                }



            }

            return string.Empty;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    /// <summary>
    /// 写入设备数据
    /// </summary>
    /// <param name="command"></param>
    /// <returns></returns>
    private async Task<bool> WriteBcrData(long equipId,string writeId)
    {
        return await _mainManager.AddWrite(new OperationWriteCommand
        {
            ProtobufType = IotProtobufType.HBC_BCR.ToString(),
            Id = writeId,
            EquipId = equipId
        }) ;
    }

   /// <summary>
   /// 重置扫码
   /// </summary>
   /// <param name="unitTag"></param>
   /// <param name="isAll">是否清除旧托盘</param>
    public void ClearBcr(CvUnitTagDto unitTag, bool isAll = true)
    {
        unitTag.BcrCommit = 0;
        unitTag.IsReadBcr = false;
        // 全部重新扫码
        unitTag.BcrID = String.Empty;
        unitTag.Message = String.Empty;
        unitTag.OriginJobNumber = 0;
        unitTag.BcrCommitJob = 0;
        unitTag.JobNumber = 0;
        unitTag.BcrCommitTimes = 0;
        unitTag.Tray1 = "";
        unitTag.Tray2 = "";
        unitTag.Tray3 = "";
        unitTag.Tray4 = "";
        unitTag.Tray5 = "";
        unitTag.Tray6 = "";
        unitTag.ErrorMaxReadBcr = 0;
        if (isAll)
        {
            unitTag.Tray1Old = "";
            unitTag.Tray2Old = "";
            unitTag.Tray3Old = "";
            unitTag.Tray4Old = "";
            unitTag.Tray5Old = "";
            unitTag.Tray6Old = "";
        }
        unitTag.ReadOkBcr = 0;
        unitTag.MaxReadBcr = 0;
        unitTag.ErrorJobNumber = 0;
    }
    /// <summary>
    /// 写入Bcr
    /// </summary>
    /// <param name="bcr"></param>
    /// <param name="bcrID">标志id</param>
    /// <param name="callCount"></param>
    /// <returns></returns>
    private async Task<int> WriteBcr(PushBcrDto bcr,string bcrID,string tray,int callCount)
    {

        if (bcr != null)
        {
            bool isRetry = false;
            if (bcr.WriteId == bcrID)
            {
                isRetry = true;
            }
            else
            {
                isRetry = false;
            }
            if (bcr.ReadingStep != BcrProcessStepType.Read_Request || bcr.ReadingStep != BcrProcessStepType.Send_ReadPacket || bcr.ReadingStep == BcrProcessStepType.Read_RetryStop)
            {
                if (isRetry)
                {
                    if (!bcr.IsReadOK || bcr.Value == tray)
                    {
                        await WriteBcrData(bcr.Id, bcrID);

                        callCount++;

                    }
                }
                else
                {

                    await WriteBcrData(bcr.Id, bcrID);
                    callCount++;
                }

            }
        }

        return callCount;
    }
    

    /// <summary>
    /// 读取 扫码枪
    /// </summary>
    /// <param name="unit"></param>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<bool> ReadBcr(CvUnitTagDto tag)
    {
        // 发送读取扫码的个数
        int callCount = 0;
        // 总光电个数
        int readMaxBcr = 0;
    

        if (!tag.IsBcrReady)
        {
            return false;
        }

        var bcrs = Bcrs.GetValueOrDefault(tag.TagNum);
        if (bcrs == null || bcrs.Count() == 0)
        {
            return false;
        }

     

        if (tag.BcrID.IsNullOrEmpty())
        {
            tag.BcrID = Guid.NewGuid().ToString();
        }
        // 创建标识符
        var bcrID = tag.BcrID;







        if (tag.IsExistTray1)
        {
            readMaxBcr = 1;
            var bcr = bcrs.FirstOrDefault(x => x.OrderNum == 1);

           callCount= await WriteBcr(bcr, bcrID,tag.Tray1Old, callCount);
        }

        if (tag.IsExistTray2)
        {
            readMaxBcr = 2;
            var bcr = bcrs.FirstOrDefault(x => x.OrderNum == 2);
            callCount = await WriteBcr(bcr, bcrID,tag.Tray2Old, callCount);
        }

        if (tag.IsExistTray3)
        {
            readMaxBcr = 3;
            var bcr = bcrs.FirstOrDefault(x => x.OrderNum == 3);
            callCount = await WriteBcr(bcr, bcrID,tag.Tray3Old, callCount);
        }

        if (tag.IsExistTray4)
        {
            readMaxBcr = 4;
            var bcr = bcrs.FirstOrDefault(x => x.OrderNum == 4);
            callCount = await WriteBcr(bcr, bcrID,tag.Tray4Old, callCount);
        }

        if (tag.IsExistTray5)
        {
            readMaxBcr = 5;
            var bcr = bcrs.FirstOrDefault(x => x.OrderNum == 5);
            callCount = await WriteBcr(bcr, bcrID,tag.Tray5Old, callCount);
        }

        if (tag.IsExistTray6)
        {
            readMaxBcr = 6;
            var bcr = bcrs.FirstOrDefault(x => x.OrderNum == 6);
            callCount = await WriteBcr(bcr, bcrID,tag.Tray6Old, callCount);
        }

        var result = callCount > 0;

        // 对总光电进行赋值
        tag.MaxReadBcr = readMaxBcr;
        if (result)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    /// <summary>
    /// 写入OcvFmt
    /// </summary>
    /// <param name="instruct"></param>
    /// <returns></returns>
    public async Task<string> WriteOcvFmtAddr(HkWriteInstruct instruct)
    {
      
        var command = new OperationWriteCommand
        {
            EquipId = instruct.Num.To<int>(),
            Data = JsonConvert.SerializeObject(instruct),
            Value = instruct.Command,
            ProtobufType = IotProtobufType.HK_OCVFMT.ToString()
        };
       var result= await _mainManager.AddWrite(command);
        if (!result)
        {
            return IotMsgConst.WriteRequestError;
        }
        return string.Empty;
    }

    /// <summary>
    /// 写入HK指令
    /// </summary>
    /// <param name="datas"></param>
    /// <returns></returns>
    public async Task<string> AddHkInstructs(List<HkWriteInstruct> datas)
    {
        foreach (var data in datas)
        {
            var fmt1 = Fmts.FirstOrDefault(x => x.Num == data.Num);

            if (fmt1 == null)
            {
               return IotMsgConst.FmtStageError;
            }

            // 充放电库位预约 | 移库预约,因为要用到堆垛机，添加到充放电内存字典中

            if (data.Command == "0102" || data.Command == "0110")
            {

                // Data为堆垛机编号，相同堆垛机不能同时预约进行
                var write = HkFMTAppointDic.Values.FirstOrDefault(x => x.Data == data.Data && x.Data.IsNotNullOrEmpty() && x.Status != 2 && x.Num != data.Num && x.Stage != data.Stage && x.Command == data.Command);
                if (write != null)
                {
                    return IotMsgConst.FmtStageSameError;
                }


                // await ScTaskValidate(data);



                if (data.Stage2 > 0)
                {
                   var fmt2= Fmts.FirstOrDefault(x => x.Num == data.Num2);


                   if( _equipValidateService.ValidateWrite(data, fmt1, fmt2) == false)
                    {
                        return IotMsgConst.FmtStageError;
                    }





                    if (!HkFMTAppointDic.ContainsKey($"{data.Num2}-{data.Stage2}"))
                    {
                        var result1 = HkFMTAppointDic.TryAdd($"{data.Num2}-{data.Stage2}", data);
                        if (!result1)
                        {
                            await Task.Delay(100);
                            HkFMTAppointDic.TryAdd($"{data.Num2}-{data.Stage2}", data);
                        }
                    }
                    else
                    {
                        var data2 = HkFMTAppointDic[$"{data.Num2}-{data.Stage2}"];
                        if (data2.Status == 2)
                        {
                            //数据进行覆盖
                            data2 = (HkWriteInstruct)data.Clone();
                        }
                        else
                        {
                            return $"{data.Num2}-{data.Stage2} {IotMsgConst.FmtStageSameError}";
                        }
                    }


                }
                else
                {
                    if (_equipValidateService.ValidateWrite(data, fmt1) == false)
                    {
                        return IotMsgConst.FmtStageError;
                    }
                }



                if (!HkFMTAppointDic.ContainsKey($"{data.Num}-{data.Stage}"))
                {

                    bool result = HkFMTAppointDic.TryAdd($"{data.Num}-{data.Stage}", (HkWriteInstruct)data.Clone());
                    if (!result)
                    {
                        await Task.Delay(100);
                        HkFMTAppointDic.TryAdd($"{data.Num}-{data.Stage}", (HkWriteInstruct)data.Clone());
                    }
                }
                else
                {
                    var data1 = HkFMTAppointDic[$"{data.Num}-{data.Stage}"];
                    if (data1.Status == 2)
                    {
                        //数据进行覆盖
                        data1 = (HkWriteInstruct)data.Clone();
                    }
                    else
                    {
                        throw new Exception($"{data.Num}-{data.Stage} {IotMsgConst.FmtStageSameError}");
                    }
                }


                //// 添加缓存
                //await _ecsCacheService.AddRedisFMTJob(data);
            }
            else
            {
                _equipValidateService.ValidateWrite(data, fmt1, null);
                return await WriteOcvFmtAddr(data);
            }
        }

        return string.Empty;

    }


}
